// CTPSubscriber.cpp: 定义应用程序的入口点。
//

#include <string>
#include <cstring>
#include <chrono>
#include <thread>
#include <iostream>
#include <boost/program_options.hpp>
#include "./include/subscriber.h"
#include "./include/INIReader.h"

using namespace std;

int main(int argc, char *argv[])
{
    boost::program_options::options_description opts("all options");
    boost::program_options::variables_map vm;
    std::string configFile = "config.ini";

    opts.add_options()("env", boost::program_options::value<std::string>(), "the env as DEV, DEV2 or PROD");
    try
    {
        boost::program_options::store(boost::program_options::parse_command_line(argc, argv, opts), vm);
    }
    catch (...)
    {
        std::cout << "Invalid option"
                  << "\n";
        return 0;
    }
    if (vm.count("env"))
    {
        std::string env = vm["env"].as<std::string>();
        if (env.compare("PROD") == 0)
        {
            configFile = std::string("config.ini");
        }
        else if (env.compare("DEV") == 0)
        {
            configFile = std::string("config.dev.ini");
        }
        else if (env.compare("DEV2") == 0)
        {
            configFile = std::string("config.dev2.ini");
        }
        else
        {
            std::cout << "Invalid env name"
                      << "\n";
            return 0;
        }
    }
    INIReader reader(configFile);
    if (reader.ParseError() < 0)
    {
        std::cout << "Config file error." << std::endl;
        return -1;
    }
    std::string quoteFrontend = reader.Get("market", "quoteAddress", "");
    std::string tradeFrontend = reader.Get("market", "tradeAddress", "");
    std::string brokerID = reader.Get("market", "brokerID", "");
    std::string userID = reader.Get("market", "userID", "");
    std::string authCode = reader.Get("market", "authCode", "");
    std::string appID = reader.Get("market", "appID", "");
    std::string password = reader.Get("market", "password", "");
    std::list<std::string> instruments = reader.GetList("subscribe", "instruments");
    std::string zmqAddress = reader.Get("rpc", "address", "");
    
    int instrumentSize = instruments.size();
    char** insts = new char* [instrumentSize];
    int i = 0;
    for (auto inst: instruments) {
        insts[i] = const_cast<char*>(inst.data());
    } 
    // insts[0] = const_cast<char*>("i2205");
    
    MarketDataSubscriber subscriber(brokerID, userID, password, quoteFrontend, insts, instrumentSize);
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }
    return 0;
}
